package com.example.thirdhomework

import android.widget.TextView
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class FifthActivity : AppCompatActivity() {

    var  seconds=0
    var running=false
    var wasRunning=false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_fifth)
        if(savedInstanceState!=null){
            seconds=savedInstanceState.getInt("seconds")
            running=savedInstanceState.getBoolean("running")
            wasRunning=savedInstanceState.getBoolean("wasRunning")
        }
        val button_start: Button =findViewById(R.id.button_start)
        val button2_stop: Button =findViewById(R.id.button2_stop)
        val button3_restart: Button =findViewById(R.id.button3_restart)
        runTimer()

        button_start.setOnClickListener{
            running = true
        }
        button2_stop.setOnClickListener{
            running=false
        }
        button3_restart.setOnClickListener{
            running=true
            seconds=0
        }

    }
    fun runTimer(){
        val hander=Handler()
        val textView3_timer: TextView =findViewById(R.id.textView3_timer)
        val runnable=object :Runnable{
            override fun run(){
                val hours=seconds/3600
                val minutes=(seconds%3600)/60
                val secs=seconds%60
                textView3_timer.text=String.format("%02d:%02d:%02d",hours,minutes,secs)
                if(running){
                    seconds++
                }
                hander.postDelayed(this,1000)
            }
        }
        hander.post(runnable)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("seconds",seconds)
        outState.putBoolean("running",running)
        outState.putBoolean("wasRunning",wasRunning)

    }
}